//
// Created by linciping on 2020/9/15.
//

#include "rtmp_pool.h"

void mallocPoll(RtmpPool *pool);

int initRtmpPool(RtmpPool *rtmpPool) {
    rtmpPool->fFmepgStruct = malloc(sizeof(FFmepgStruct) * SIZE);
    rtmpPool->size = 0;
    rtmpPool->maxSize = SIZE;
    return 0;
}

int add(RtmpPool *rtmpPool, FFmepgStruct ffmepgStruct) {
    if (rtmpPool->size >= (rtmpPool->maxSize * 0.8)) {
        mallocPoll(rtmpPool);
    }
    rtmpPool->fFmepgStruct[rtmpPool->size] = ffmepgStruct;
    rtmpPool->size++;
    return rtmpPool->size - 1;
}

void mallocPoll(RtmpPool *pool) {
    int newSize = pool->maxSize + SIZE;
    FFmepgStruct *newData = malloc(newSize * sizeof(FFmepgStruct));
    FFmepgStruct *oldData = pool->fFmepgStruct;
    for (int i = 0; i < pool->size; ++i) {
        newData[i] = oldData[i];
    }
    free(oldData);
    pool->fFmepgStruct = newData;
    pool->maxSize = newSize;
}

int removeItem(RtmpPool *rtmpPool, const char *rtspUrl) {
    int index = indexOf(*rtmpPool, rtspUrl);
    if (index >= 0) {
        for (int i = index; i < rtmpPool->size; ++i) {
            rtmpPool->fFmepgStruct[i - 1] = rtmpPool->fFmepgStruct[i];
        }
        rtmpPool->size--;
    }
    return -1;
}

FFmepgStruct *get(RtmpPool rtmpPool, const char *rtspUrl) {
    for (int i = 0; i < rtmpPool.size; ++i) {
        FFmepgStruct *ffmepgStruct = &rtmpPool.fFmepgStruct[i];
        if (equals(ffmepgStruct->rtmpUrl, rtspUrl) == 0) {
            return ffmepgStruct;
        }
    }
    return NULL;
}

int indexOf(RtmpPool rtmpPool, const char *rtspUrl) {
    for (int i = 0; i < rtmpPool.size; ++i) {
        FFmepgStruct *ffmepgStruct = &rtmpPool.fFmepgStruct[i];
        if (equals(ffmepgStruct->rtmpUrl, rtspUrl) == 0) {
            return i;
        }
    }
    return -1;
}

int equals(const char *rtspUrl1, const char *rtspUrl2) {
    return strcmp(rtspUrl1, rtspUrl2);
}

int length(RtmpPool rtmpPool) {
    return rtmpPool.size;
}

int clear(RtmpPool *rtmpPool) {
    free(rtmpPool->fFmepgStruct);
    free(rtmpPool);
    return 0;
}

